package com.xmcc.common;

import com.xmcc.exception.ParamException;
import com.xmcc.exception.PermissionsException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class PermissionsExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) {
        String url = request.getRequestURL().toString();
        System.out.println(request.getRequestURL());
        log.info(url);
        String defaultMessage="系统繁忙,稍后再试";
        ModelAndView modelAndView;
        //在项目中所有的ajax请求的路径都以.json结尾，页面请求的路径以.page结尾：
        if (url.endsWith(".json")){ //ajax局部刷新请求，所以有异常用户也看不懂，给开发人员看的
            ResultJson resultJson = ResultJson.fail(e.getMessage());
            log.error("json exception","url:"+url,e);
            modelAndView = new ModelAndView("jsonView",resultJson.toMap());
            return  modelAndView;
        }else if (url.endsWith(".page")){ // 页面请求的，开发人员可以看到，用户也可以看到
            //如果是自己的异常，就输出自己异常的信息：
            if (e instanceof PermissionsException || e instanceof ParamException){
                ResultJson resultJson = ResultJson.fail(e.getMessage());
                log.error("page exception","url:"+url,e);
                modelAndView = new ModelAndView("exception",resultJson.toMap());
                return modelAndView;
            }else { //如果不是自己的异常，就输出自己默认异常的信息：
                ResultJson resultJson = ResultJson.fail(defaultMessage);
                log.error("jdk exception","url:"+url,e);
                modelAndView = new ModelAndView("exception",resultJson.toMap());
                return modelAndView;
            }
        }else { //既不是.json和,page结尾的：
            ResultJson resultJson = ResultJson.fail(e.getMessage());
            log.error("jdk exception","url:"+url,e);
            modelAndView = new ModelAndView("exception",resultJson.toMap());
            return modelAndView;
        }
    }
}
